package com.wtwd.wtwddevice.mq;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.properties.MqProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author mjy
 * @date 2024/4/28 16:05
 */
@Service
@Slf4j
public class PushMsgService {

    @Resource
    private MqProperties mQproperties;

    private DefaultMQProducer producer;

    private String deviceMsgTag;

    public DefaultMQProducer getProducer() {
        return producer;
    }

    @PostConstruct
    public void init() {
        producer = new
                DefaultMQProducer(mQproperties.getDeviceServiceProduceGroup());
        producer.setNamesrvAddr(mQproperties.getNamesrvAddr());
        this.deviceMsgTag = mQproperties.getDeviceMsgTag();
        producer.setSendMsgTimeout(5000);
        producer.setRetryTimesWhenSendFailed(3);
        try {
            producer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void push(String topic, String tag, MessageBase messageBase) {
        Message msg = null;
        try {
            byte[] message = messageBase.serialize();
            msg = new Message(topic,
                    tag,
                    message
            );
            SendResult sendResult = getProducer().send(msg);
            log.info("topic:{},tag:{}设备处理服务器推送到设备服务器{},device:{},cmd:{}",topic,tag,sendResult.toString() , messageBase.getDeviceKey(),messageBase.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void push(String topic, String tag, Object content) {
        Message msg = null;
        try {
            String s = JSONObject.toJSONString(content);
            byte[] message = s.getBytes();
            msg = new Message(topic,
                    tag,
                    message
            );
            SendResult sendResult = getProducer().send(msg);
            log.info("{},{}",sendResult.toString() , s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void pushToDevice(String topic, MessageBase messageBase) {
        push(topic, deviceMsgTag, messageBase);
    }


}
